<template>
  <div>
    <div class="table-toolbar" v-if="hasToolbar">
      <div class="table-toolbar-left">
        <slot name="toolbarBtn"></slot>
      </div>
      <!-- 列表数据，删除，刷新...操作 -->
      <div class="table-toolbar-right flex-center">
        <template v-if="multipleSelection.length > 0">
          <!-- 删除选中 -->
          <el-tooltip effect="dark" content="删除选中" placement="top">
            <el-icon class="columns-setting-icon" @click="delSelection(multipleSelection)">
              <Delete />
            </el-icon>
          </el-tooltip>
          <el-divider direction="vertical" />
          <!-- 还原选中 -->
          <el-tooltip effect="dark" content="还原选中" placement="top">
            <el-icon class="columns-setting-icon" @click="restoreSelection(multipleSelection)">
              <RefreshLeft />
            </el-icon>
          </el-tooltip>
          <el-divider direction="vertical" />
        </template>
        <el-tooltip effect="dark" content="刷新" placement="top">
          <el-icon class="columns-setting-icon" @click="refresh">
            <Refresh />
          </el-icon>
        </el-tooltip>
        <el-divider direction="vertical" />
        <el-tooltip effect="dark" content="列设置" placement="top">
          <el-dropdown :hide-on-click="false" size="small" trigger="click">
            <el-icon class="columns-setting-icon">
              <Setting />
            </el-icon>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-for="c in columns" :key="c.prop">
                  <el-checkbox v-model="c.visible" :label="c.label" />
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-tooltip>
      </div>
    </div>

    <!-- 列表数据显示 -->
    <el-table 
      max-height="400" 
      class="mgb20" 
      :style="{ width: '100%' }" 
      border 
      :data="tableData" 
      :row-key="rowKey"
      @selection-change="handleSelectionChange" 
      table-layout="auto"
    >
      <!-- 可选框 -->
      <el-table-column 
        type="selection" 
        align="center" 
        #default="{ row, column, $index }" 
        v-if="selection" 
        width="55" 
      />
      
      <!-- 循环列 -->
      <template v-for="item in columns" :key="item.prop">
        <el-table-column 
          :fixed="item.fixed === 'right' ? 'right' : undefined" 
          v-if="item.visible" 
          :prop="item.prop" 
          :label="item.label" 
          :width="item.width"
          :type="item.type" 
          :align="item.align || 'center'"
        >
          <!-- 序号 -->
          <template #default="{ row, column, $index }" v-if="item.type === 'index'">
            {{ getIndex($index) }}
          </template>

          <!-- 日期类型 -->
          <template #default="{ row, column, $index }" v-else-if="item.type === 'date'">
            {{ convertToBeijingTime(row[item.prop]) }}
          </template>

          <!-- 标签 -->
          <template #default="{ row, column, $index }" v-else-if="item.type === 'tag'">
            <el-tag :type="item.tagType" :effect="item.effect">
              {{ row[item.prop] }}
            </el-tag>
          </template>

          <!-- 图片类型 -->
          <template #default="{ row, column, $index }" v-else-if="item.type === 'img'">
            <img 
              :src="row[item.prop]" 
              alt="图片" 
              :style="{ width: item.imgWidth, height: item.imgHeight }" 
            />
          </template>

          <!-- 普通文本以及插槽 -->
          <template #default="{ row, column, $index }" v-else>
            <slot 
              :name="item.prop" 
              :row="row" 
              :index="$index"
            >
              {{ row[item.prop] }}
            </slot>
          </template>
        </el-table-column>
      </template>
    </el-table>
    
    <!-- 分页组件 -->
    <el-pagination
      v-if="rp.isPaged"
      :current-page="rp.page" 
      v-model:page-size="pageSizeModel" 
      :page-sizes="pageSizes"
      :background="true"
      :layout="layout" 
      :total="rp.total" 
      @size-change="handlePageSizeChange"
      @current-change="handleCurrentChange" 
    />
  </div>
</template>
<script setup lang="ts">
import { toRefs, PropType, ref, computed } from 'vue'
import { Delete, Refresh, Setting } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus'
import { toZonedTime, format } from 'date-fns-tz'
import { RQ } from '@/types/rq'

// 定义组件属性
const props = defineProps({
 // === 表格数据相关 ===
  tableData: {
    type: Array as PropType<any[]>,
    default: () => []
  },
  columns: {
    type: Array as PropType<any[]>,
    default: () => []
  },
  rowKey: {
    type: String,
    default: 'id'
  },

  // === 显示控制相关 ===
  hasToolbar: {
    type: Boolean,
    default: true
  },
  selection: {
    type: Boolean,
    default: true
  },

  // === 分页相关 ===
  layout: {
    type: String,
    default: 'total, prev, pager, next, jumper, sizes'
  },
  pageSizes: {
    type: Array<number>,
    default: () => [5, 10, 20, 30, 40, 50, 100]
  },
  rp: {
    type: Object as PropType<RQ<any>>,
    required: true
  },

  // === 回调函数 ===
  queryData: {//查询
    type: Function as PropType<(rq: RQ<any>) => void>,
    default: () => {}
  },
  delData: {//删除
    type: Function as PropType<(ids: number[]) => Promise<any>>,
    default: () => {}
  },
  restoreData: {//恢复
    type: Function as PropType<(ids: number[]) => Promise<any>>,
    default: () => {}
  }
})

const { 
  tableData,
  columns,
  rowKey,
  hasToolbar,
  layout,
  rp,
  pageSizes
} = toRefs(props)

const emit = defineEmits<{
  (e: 'update:rp', value: RQ<any>): void
}>()

const pageSizeModel = computed<number>({
  get() {
    return rp.value.size
  },
  set(val) {
    const newRq = { ...rp.value, size: val, page: 1 }
    emit('update:rp', newRq)
    
    // 自动查询数据
    props.queryData?.(newRq) // 使用可选链操作符
  }
})

// 初始化列的可见性
columns.value.forEach((item) => {
  if (item.visible === undefined) {
    item.visible = true
  }
})

// 当选择项发生变化时会触发该事件
const multipleSelection = ref<any[]>([])
const handleSelectionChange = (selection: any[]) => {
  multipleSelection.value = selection
}

// 处理页面大小变化
const handlePageSizeChange = (val: number) => {
  const newRq = { ...rp.value, size: val, page: 1 }
  emit('update:rp', newRq)
  props.queryData?.(newRq)
}

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  const newRq = { ...rp.value, page: val }
  emit('update:rp', newRq)
  props.queryData?.(newRq)
}

// 刷新表格
const refresh = () => {
  props.queryData?.(rp.value)
}

// 转换时间为北京时间
function convertToBeijingTime(isoTime: string): string {
  try {
    const timeZone = 'Asia/Shanghai'
    const zonedTime = toZonedTime(new Date(isoTime), timeZone)
    return format(zonedTime, "yyyy-MM-dd HH:mm:ss", { timeZone })
  } catch (error) {
    return isoTime
  }
}

// 删除选中项的逻辑
const delSelection = async (selectedItems: any[]) => {
  try {
    await ElMessageBox.confirm('确定要删除选中的项吗？', '提示', {
      type: 'warning'
    })
    const ids = selectedItems.map(item => item.id)
    // 调用删除函数
    if (props.delData) {
      await props.delData(ids)
      // 删除成功后刷新数据
      props.queryData?.(rp.value)
    }
  } catch (error) {
    // 用户取消或删除失败
    console.log('删除操作已取消或失败')
  }
}

// 还原选中项的逻辑
const restoreSelection = async (selectedItems: any[]) => {
  try {
    await ElMessageBox.confirm('确定要还原选中的项吗？', '提示', {
      type: 'warning'
    })
    const ids = selectedItems.map(item => item.id)
    // 调用删除函数
    if (props.restoreData) {
      await props.restoreData(ids)
      // 删除成功后刷新数据
      props.queryData?.(rp.value)
    }
  } catch (error) {
    // 用户取消或还原失败
    console.log('还原操作已取消或失败')
  }
}
// 计算序号
const getIndex = (index: number) => {
  return index + 1 + (rp.value.page - 1) * rp.value.size
}
</script>

<style scoped>
.el-table--border .el-table__cell:first-child .cell {
  padding: 0;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-bottom: 10px;
}

.columns-setting-icon {
  display: block;
  font-size: 18px;
  cursor: pointer;
  color: #676767;
}
</style>

<style>
.table-header .cell {
  color: #333;
}
</style>